//
//  WBRefreshControl.swift
//  wbxm
//
//  Created by apple on 15/12/23.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SnapKit

enum WBRefreshStatue: Int {
    //默认状态
    case Normal = 0
    //用户下拉临界值  还没有松手刷新的状态
    case Pulling = 1
    //正在刷新的状态
    case Refreshing = 2
}

private let RefreshViewHeight: CGFloat = 60

class WBRefreshControl: UIControl {
    //定义属性 保存上一次刷新的状态
    var oldStatue: WBRefreshStatue = .Normal

    // MARK:定义外部模型属性
    var statue: WBRefreshStatue = .Normal {
        didSet{
            //根据不同状态  更改显示的逻辑
            switch statue {
            case .Pulling:
                print("准备起飞")
                tipLabel.text = "准备起飞"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                print("正在起飞")
                tipLabel.text = "正在起飞"
                
                //影藏剪头  显示转动的小菊花
                arrowIcon.hidden = true
                loadIcon.startAnimating()
                
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    //修改contentInset
                    var inset = self.scrollView!.contentInset
                    inset.top += RefreshViewHeight
                    self.scrollView?.contentInset = inset
                })

                
                
                
                //应该主动触发control 的方法响应事件
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
            case .Normal:
                //回到从前最初的状态  重置操作
                arrowIcon.hidden = false
                loadIcon.stopAnimating()
                print("下拉起飞")
                tipLabel.text = "下拉起飞"
                
                //修改contentInset
                if oldStatue == .Refreshing {
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scrollView!.contentInset
                        inset.top -= RefreshViewHeight
                        self.scrollView?.contentInset = inset
                    })
                   
                }
               
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(2 * M_PI))
                })
            }
            
//            所有的设置结束后 保存上一次的刷新状态
            oldStatue = statue
        }
    }
    
    //实现KVO方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(change)
//        print("--------")
//        print(scrollView?.contentInset)
        //1 获取tableViewcontent临界值
        var insetTop = scrollView?.contentInset.top ?? 0
        var condationValue = -(RefreshViewHeight + insetTop)
        //2获取tableVIew的contentoffset
        let offsetY = scrollView?.contentOffset.y ?? 0
        
        if scrollView!.dragging {
            
            //3比较对应的临界值 和 位移的大小
            if statue == .Normal && offsetY < condationValue {
                //进入用户下拉临界值  还没有松手刷新的状态
                statue = .Pulling
            } else if statue == .Pulling && offsetY > condationValue {
                //进入默认状态
                statue = .Normal
            }
        }else {
            //不是正在拉拽的状态 并且 当前的视图的statue 是pulling状态 在执行刷新操作
        
            if statue == .Pulling {
                statue = .Refreshing
            }
        }
    }
    
    func endefreshing() {
        
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(1) * Int64(NSEC_PER_MSEC))
        
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.statue = .Normal
        }
        
    }
    
    //view的生命周期方法   将要移动到父视图上
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        //可以获取到当前控件的父视图
        //1 获取tableView
        if let myFather = newSuperview as? UIScrollView {
            //如果父视图能够转化为 滚动视图
            //观察 滚动视图的contentoffset
            self.scrollView = myFather
            //设置KVO
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
            
        }
       
    }
    
    //移除KVO观察
    deinit{
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    //定义属性,  记录父视图
    var scrollView: UIScrollView?
    
    // MARK:重写构造方法
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -RefreshViewHeight, width: screenW, height: RefreshViewHeight)
        super.init(frame: rect)
        setupUI()
        //设置颜色
        backgroundColor = UIColor.randomeColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:设置页面和布局
    private func setupUI() {
        //添加子视图
        addSubview(tipLabel)
        addSubview(arrowIcon)
        addSubview(loadIcon)
        
        //设置约束
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLabel.snp_left).offset(-5)
            make.centerY.equalTo(tipLabel.snp_centerY)
        }
        
        loadIcon.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
        
        
    }
    
    // MARK:懒加载所有的子视图
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var tipLabel: UILabel = UILabel(title: "下拉起飞", color: UIColor.darkGrayColor(), fontSize: 14)

    //小菊花
    private lazy var loadIcon: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    

}
